package com.cloudcc.mobile.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.RequestListener;
import com.cloudcc.cloudframe.util.ListUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.ReceiverConstant;
import com.cloudcc.mobile.dao.impl.BeauInfoShareSet;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity.ObjMenu;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity.TabLabel;
import com.cloudcc.mobile.event.refresh.RefreshEntiityListEvent;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.presenter.BeauPresenter;
import com.cloudcc.mobile.presenter.OtherPresenter;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.market.MarketActivityInfoActivity;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.NewWebView;
import com.cloudcc.mobile.view.web.NewWebViewActivity;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy.MonitorParam;
import com.litesuits.android.log.Log;
import com.mypage.utils.SaveTemporaryData;
import com.mypage.view.activity.beautMore.ChangePersonActivity;
import com.mypage.view.activity.beautMore.ChangeRecordActivity;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * 一个简单的ListViewAdapter适配器写法，内含跳转方法。
 *
 * @author
 *
 */
public class NewMoreAdapter extends BaseAdapter  {

	// 上下文
	private Context context;

	// List表
	private String mEntityId,mEntityNameID,from,Mshijian,jsonname;
	private BeauInfoEntity mBeauInfo;
	private String mEns = RunTimeManager.getInstance().getlanguage();
	private BeauPresenter mBeauPresenter = new BeauPresenter();
	boolean isMeFollow = false;
	List<ObjMenu> jsonObject;
	List<BeauInfoEntity.ObjChange> mJot;
	List<String> mList = null;
	List<String> btnList = null;
	public List<TabLabel> tabLabel;
	public String mPname;
	public String mObjId;
	public String mObjName;
	public String mPersionName;
	public String mPersionNameIds;
	public String OwerName ;
	public String OwerNameID ;

	public String mType;
	public int mJump = 0;
	public int mTypes;
	private boolean ishaveshare = false;//是否有分享按钮
	private int sharecod = 0;//为分享后面的按钮点击事件添加标记位 默认为0，如果有分享按钮为1
	public List<BeauInfoEntity.ObjChange.TypeChange> recordList;
	String fenxiang = "分享";
	String qxgz = "取消关注";
	String gzjl = "关注记录";
	String scjl = "删除记录";
	String gdcz = "更多操作";

	private boolean boolShowCall = false;
	// 构造函数
	public NewMoreAdapter(String mPersionName,String mPersionNameIds,List<BeauInfoEntity.ObjChange> mJot,Context context, String mEntityId,String mEntityNameID,List<ObjMenu> jsonObject,String from,boolean isMeFollow,String Mshijian,String jsonname,List<TabLabel> tabLabel,String mPname,String mObjId,String mObjName) {
		this.mPersionName = mPersionName;
		this.mPersionNameIds = mPersionNameIds;
		this.mJot = mJot;
		this.context = context;
		this.mEntityId = mEntityId;
		this.mEntityNameID = mEntityNameID;
		this.jsonObject = jsonObject;
		this.from = from;
		this.Mshijian =  Mshijian;
		this.isMeFollow  = isMeFollow;
		this.jsonname = jsonname;
		this.tabLabel = tabLabel;
		this.mPname = mPname;
		this.mObjId = mObjId;
		this.mObjName = mObjName;
		mList = new ArrayList<String>();
		btnList = new ArrayList<String>();
//		mList.add("分享");

		if ("showCall".equals(SaveTemporaryData.mBeauInfoTui)){
			boolShowCall = true;
			if (SaveTemporaryData.isCalling){
				mList.add("电话");
			}
		}else if ("hintCall".equals(SaveTemporaryData.mBeauInfoTui)){
			boolShowCall = false;
		}

		try {
			for (int i = 0; i < mJot.size(); i++) {
				btnList.add(mJot.get(i).buttonName);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			for (int i = 0; i < jsonObject.size(); i++) {
				mList.add(jsonObject.get(i).relationName);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

		if ("en".equals(mEns)) {
			qxgz = "Un Attention";
			gzjl = "Follow";
			scjl = "Delete Record";
			gdcz = "More operations";
			fenxiang = "share";
		} else {
			qxgz = "取消关注";
			gzjl = "关注记录";
			scjl = "删除记录";
			gdcz = "更多操作";
			fenxiang = "分享";
		}
		if(isMeFollow){
			mList.add(qxgz);
		}else{
			mList.add(gzjl);
		}
		if(null == btnList || btnList.size() ==0 ){
			mJump = 0;
		}
		String s = null;
		if(btnList != null && btnList.size() != 0){
			s = btnList.get(0);
		}
		if (btnList.size()==1){
			mJump = 1;
			if (s.contains("人")){
				if ("en".equals(mEns)) {
					mList.add("Change owner");
				} else {
					mList.add("更改所有人");
				}

				 OwerName = mJot.get(0).ownerList.get(0).ownerccname;
				 OwerNameID = mJot.get(0).ownerList.get(0).ownerid;
				mTypes = 1;
			}
			if (s.contains("型")){
				if ("en".equals(mEns)) {
					mList.add("Change the record type");
				} else {
					mList.add("更改记录类型");
				}
				 recordList = mJot.get(0).recordList;
				mType = mJot.get(0).recordDefault;
				mTypes = 2;
			}

		}else if(btnList.size()==2){
			mJump = 2;
			String ss1 = btnList.get(0);
			String ss = btnList.get(1);
			if (ss.contains("人")){
				if ("en".equals(mEns)) {
					mList.add("Change owner");
				} else {
					mList.add("更改所有人");
				}
				OwerName = mJot.get(1).ownerList.get(0).ownerccname;
				OwerNameID = mJot.get(1).ownerList.get(0).ownerid;
			}else{
				if ("en".equals(mEns)) {
					mList.add("Change the record type");
				} else {
					mList.add("更改记录类型");
				}
				recordList = mJot.get(1).recordList;
				mType = mJot.get(1).recordDefault;
			}
			if (ss1.contains("人")){
				if ("en".equals(mEns)) {
					mList.add("Change owner");
				} else {
					mList.add("更改所有人");
				}
				OwerName = mJot.get(0).ownerList.get(0).ownerccname;
				OwerNameID = mJot.get(0).ownerList.get(0).ownerid;
			}else{
				if ("en".equals(mEns)) {
					mList.add("Change the record type");
				} else {
					mList.add("更改记录类型");
				}

				recordList = mJot.get(0).recordList;
				mType = mJot.get(0).recordDefault;
			}
		}

		if(StringUtils.equalsIgnoreCase(mEntityNameID, "contact") || StringUtils.equalsIgnoreCase(mEntityNameID, "lead") || StringUtils.equalsIgnoreCase(mEntityNameID, "account")){
			mList.add(fenxiang);
			ishaveshare = true;
			sharecod = 1;
		}
		mList.add(scjl);

		setBtn();
	}
	public void setBtn(){

}
	// List表单的总数
	public int getCount() {
		return mList.size();
	}

	// 位于position处的List表单的一项
	public Object getItem(int position) {
		return mList.get(position);
	}

	// List表单的各项的索引
	public long getItemId(int position) {
		return position;
	}

	// 最重要的获得视图内容方法
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewCache viewCache = null;

		if (convertView == null) {
			viewCache = new ViewCache();

			// LayoutInflater布局填充器，名副其实，见名知意。
			convertView = LayoutInflater.from(context).inflate(
					R.layout.new_select_list_item, null);

			// 根据布局并通过控件各自的ID找控件。

			viewCache.name = (TextView) convertView
					.findViewById(R.id.new_select_item_name);
			viewCache.imageView = (ImageView) convertView
					.findViewById(R.id.huodong_tupian);

			// 为每项的TextView加个Tag
			viewCache.name.setTag(position);

			// 为convertView添加标记
			convertView.setTag(viewCache);

		} else {

			// 根据标记找到viewCache，达到缓存的目的（软引用）
			viewCache = (ViewCache) convertView.getTag();
		}

		// 给TextView设置内容
		viewCache.name.setText(mList.get(position));
		final String name = mList.get(position);

		//给imageview设置图片

				 try {
					 int bg_id =1;
					 String backgid = "tu1";
					 Class drawable = R.drawable.class;
					 backgid = "tu" + ((position) % 5);
					Field field = drawable.getField(backgid);
					bg_id = field.getInt(field.getName());


				if((mList.get(position).contains("关注"))||(mList.get(position).contains("Attention"))){
					viewCache.imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.guanzhu));
				}else if((mList.get(position).contains("删除"))||(mList.get(position).contains("Delete"))){
					viewCache.imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.shanchujilu));
				}else{
					viewCache.imageView.setImageBitmap(null);
					viewCache.imageView.setBackgroundResource(bg_id);
				}
				 } catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

		// 添加监听事件
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Activity activity = (Activity)context;
	            activity.finish();
				if (mJump==0){
					setNoBtn(position);
				}else if(mJump==2){
					setHaveBtn(position);
				}else if(mJump==1){
					setOneBtn(position,mTypes);
				}

			}


		});


		return convertView;
	}
//	private void postShare() {
//		PostShare event = new PostShare();
//		event.isshare = true;
//		EventEngine.post(event);
//		((Activity) context).finish();
//	}

	// 辅助缓存类
	class ViewCache {
		TextView  name;
		ImageView imageView;
	}

	private void followEntity() {
		new OtherPresenter().followRecord(mEntityId, isMeFollow,
				new RequestListener() {

					@Override
					public void onSuccess(Object arg0) {
						isMeFollow = !isMeFollow;
						if ("en".equals(mEns)) {
							Toast.makeText(
									context,
									isMeFollow ? "Concerned about success"
											: "Cancel attention to success", 0)
									.show();
						} else {
							Toast.makeText(context,
									isMeFollow ? "关注成功" : "取消关注成功", 0).show();
						}

						RefreshEntiityListEvent event = new RefreshEntiityListEvent();
						event.setOk(true);
						event.setData(new String[] { mEntityId,
								String.valueOf(isMeFollow) });
						EventEngine.post(event);
						((Activity) context).finish();
					}

					@Override
					public void onFailure(ErrorInfo arg0) {
						String errormessage = arg0.getErrorMessage();
						Toast.makeText(context, errormessage, 0).show();

					}
				});
	}
	// 删除记录
		private void deleteEntity() {

			if (ListUtils.isEmpty(tabLabel)
					||tabLabel.get(0) == null) {
				if ("en".equals(mEns)) {
					Toast.makeText(context, "Failed to delete。。。", 0).show();
				} else {
					Toast.makeText(context, "删除失败。。。", 0).show();
				}

				return;
			}
			TabLabel tabLabel1 = tabLabel.get(0);
			mBeauPresenter.deleteEntity(mEntityId, tabLabel1.objectapiname,
					new RequestListener() {
						@Override
						public void onSuccess(Object arg0) {
							try {
								Intent intent = new Intent(
										ReceiverConstant.RECEIVE_DELETE);
								context.sendBroadcast(intent);
								if ("webview".equals(from)) {
									NewWebViewActivity.instance.finish();
									Intent intent1 = new Intent(context,
											NewWebViewActivity.class);
									intent.putExtra("MyPushMessageReceiver",
											"event");
									Mshijian = "p";
									context.startActivity(intent1);
								}
								// 任务
								if ("matter".equals(Mshijian)) {
									NewWebViewActivity.instance.finish();
									Intent intent2 = new Intent(context,
											NewWebViewActivity.class);
									intent2.putExtra("MyPushMessageReceiver",
											"task");
									from = "o";
									context.startActivity(intent2);
								}
								if ("newwebview".equals(from)) {
									NewWebView.instance.finish();
									Intent intent2 = new Intent(context,
											NewWebView.class);
									// intent2.putExtra("MyPushMessageReceiver",
									// "task");
									from = "o";
									context.startActivity(intent2);
								}

								((Activity) context).finish();
								BeauInfoActivity.inatance.finish();
							} catch (Exception e) {
							}
						}

						@Override
						public void onFailure(ErrorInfo arg0) {
							Toast.makeText(context, arg0.getErrorMessage(), 0).show();
//							if ("en".equals(mEns)) {
//								Toast.makeText(context, "Failed to delete。。。", 0)
//										.show();
//							} else {
//								Toast.makeText(context, "删除失败...", 0).show();
//							}

						}
					});
		}
		public void setNoBtn(int position){

			if ("add".equals(SaveTemporaryData.mSmart)){
				if (boolShowCall){
					if (position == 0){
						SaveTemporaryData.mSmart = "call";
						return;
					}

					position = position-1;
				}
			}




			if (position < ListUtils.getSize(jsonObject)) {
				ObjMenu objMenu = jsonObject.get(position);
				if (StringUtils.equals(objMenu.relationUrl, "www.campaign.com")) {


					String name = jsonname;
					Log.d("popwindows", name + "www.campaign.com");
					Intent intent = new Intent(context,
							MarketActivityInfoActivity.class);
					intent.putExtra(ExtraConstant.EXTRA_NAME, name);
					intent.putExtra(ExtraConstant.EXTRA_ID, mEntityId);
					context.startActivity(intent);
				} else {
					Intent intent = new Intent(context,
							CloudWebViewActivity.class);
					Log.d("popwindows", "CloudWebViewActivity" + "跳轉小網頁");
					intent.putExtra(
							ExtraConstant.EXTRA_URL,
							UrlManager.getManager().addReturnUrl(
									UrlManager.getManager().getUrlByRoot(
											objMenu.relationUrl)));
					MonitorParam monitorParam = new MonitorParam(new String[] {
							"m=save", "m=query", "type=remark" },
							WebSyncDefaultProxy.STEP_START, new String[] {
							"/WeiXin_index.action", "m=query" }, true,
							WebSyncDefaultProxy.STEP_OVERRIDEURL);
					intent.putExtra(
							"callback",
							WebSyncDefaultProxy
									.creatDefaultProxy(
											ReceiverConstant.RECEIVE_REFRESH)
									.addMonitorParam(monitorParam)
									.addHomeMonitor());
					context.startActivity(intent);
				}
			} else if (position == ListUtils.getSize(jsonObject)) {// 跟随或者取消跟随
				Log.d("popwindows", "跟随或者取消跟随");
				followEntity();
			} else if (position == ListUtils
					.getSize(jsonObject) + 1 && ishaveshare) {
				BeauInfoShareSet.getInstance().setShareDao();

			} else if (position == ListUtils
					.getSize(jsonObject) + 1 + sharecod) {// 删除
				Log.d("shanchu", "删除");
				Log.d("popwindows", "删除");

				deleteEntity();

			}
		}
		public void setHaveBtn(int position){

			if ("add".equals(SaveTemporaryData.mSmart)){
				if (boolShowCall){
					if (position == 0){
						SaveTemporaryData.mSmart = "call";
						return;
					}

					position = position-1;
				}
			}


			if (position < ListUtils.getSize(jsonObject)) {
				ObjMenu objMenu = jsonObject.get(position);
				if (StringUtils.equals(objMenu.relationUrl, "www.campaign.com")) {


					String name = jsonname;
					Log.d("popwindows", name + "www.campaign.com");
					Intent intent = new Intent(context,
							MarketActivityInfoActivity.class);
					intent.putExtra(ExtraConstant.EXTRA_NAME, name);
					intent.putExtra(ExtraConstant.EXTRA_ID, mEntityId);
					context.startActivity(intent);
				} else {
					Intent intent = new Intent(context,
							CloudWebViewActivity.class);
					Log.d("popwindows", "CloudWebViewActivity" + "跳轉小網頁");
					intent.putExtra(
							ExtraConstant.EXTRA_URL,
							UrlManager.getManager().addReturnUrl(
									UrlManager.getManager().getUrlByRoot(
											objMenu.relationUrl)));
					MonitorParam monitorParam = new MonitorParam(new String[] {
							"m=save", "m=query", "type=remark" },
							WebSyncDefaultProxy.STEP_START, new String[] {
							"/WeiXin_index.action", "m=query" }, true,
							WebSyncDefaultProxy.STEP_OVERRIDEURL);
					intent.putExtra(
							"callback",
							WebSyncDefaultProxy
									.creatDefaultProxy(
											ReceiverConstant.RECEIVE_REFRESH)
									.addMonitorParam(monitorParam)
									.addHomeMonitor());
					context.startActivity(intent);
				}
			} else if (position == ListUtils.getSize(jsonObject)) {// 跟随或者取消跟随
				Log.d("popwindows", "跟随或者取消跟随");
				followEntity();
			} else if (position == ListUtils
					.getSize(jsonObject) + 3 + + sharecod) {// 删除
				Log.d("shanchu", "删除");
				Log.d("popwindows", "删除");
				deleteEntity();
			} else if (position == ListUtils
					.getSize(jsonObject) + 1) {
//				BeauInfoShareSet.getInstance().setChangeDao();
				Intent intents = new Intent(context, ChangeRecordActivity.class);
				intents.putExtra("LIST", (Serializable) recordList);
				intents.putExtra("mEntityId",mEntityId);
				intents.putExtra("mType",mType);
				context.startActivity(intents);

			}else if (position == ListUtils
					.getSize(jsonObject) + 2) {
				Intent intents = new Intent(context, ChangePersonActivity.class);
				intents.putExtra("mPersionName",mPersionName);
				intents.putExtra("mPersionNameIds",mPersionNameIds);
				intents.putExtra("OwerName",OwerName);
				intents.putExtra("OwerNameID",OwerNameID);

				intents.putExtra("mPname",mPname);
				intents.putExtra("mObjId",mObjId);
				intents.putExtra("mObjName",mObjName);
				intents.putExtra("mEntityNameIDs",mEntityNameID);
				intents.putExtra("mEntityIds",mEntityId);

				context.startActivity(intents);

			}else if (position == ListUtils
					.getSize(jsonObject) + 3 && ishaveshare) {//分享
				BeauInfoShareSet.getInstance().setShareDao();

			}
			else if (SaveTemporaryData.isCalling){
////				if (position == ListUtils.getSize(jsonObject) + 4){
//					SaveTemporaryData.mSmart = "call";
////				}

			}
		}
		public void setOneBtn(int position,int mT){
			if ("add".equals(SaveTemporaryData.mSmart)){
				if (boolShowCall){
					if (position == 0){
						SaveTemporaryData.mSmart = "call";
						return;
					}

					position = position-1;
				}
			}




			if (position < ListUtils.getSize(jsonObject)) {
				ObjMenu objMenu = jsonObject.get(position);
				if (StringUtils.equals(objMenu.relationUrl, "www.campaign.com")) {


					String name = jsonname;
					Log.d("popwindows", name + "www.campaign.com");
					Intent intent = new Intent(context,
							MarketActivityInfoActivity.class);
					intent.putExtra(ExtraConstant.EXTRA_NAME, name);
					intent.putExtra(ExtraConstant.EXTRA_ID, mEntityId);
					context.startActivity(intent);
				} else {
					Intent intent = new Intent(context,
							CloudWebViewActivity.class);
					Log.d("popwindows", "CloudWebViewActivity" + "跳轉小網頁");
					intent.putExtra(
							ExtraConstant.EXTRA_URL,
							UrlManager.getManager().addReturnUrl(
									UrlManager.getManager().getUrlByRoot(
											objMenu.relationUrl)));
					MonitorParam monitorParam = new MonitorParam(new String[] {
							"m=save", "m=query", "type=remark" },
							WebSyncDefaultProxy.STEP_START, new String[] {
							"/WeiXin_index.action", "m=query" }, true,
							WebSyncDefaultProxy.STEP_OVERRIDEURL);
					intent.putExtra(
							"callback",
							WebSyncDefaultProxy
									.creatDefaultProxy(
											ReceiverConstant.RECEIVE_REFRESH)
									.addMonitorParam(monitorParam)
									.addHomeMonitor());
					context.startActivity(intent);
				}
			} else if (position == ListUtils.getSize(jsonObject)) {// 跟随或者取消跟随
				Log.d("popwindows", "跟随或者取消跟随");
				followEntity();
			} else if (position == ListUtils
					.getSize(jsonObject) + 2 + sharecod) {// 删除
				Log.d("shanchu", "删除");
				Log.d("popwindows", "删除");
				deleteEntity();
			} else if (position == ListUtils
					.getSize(jsonObject) + 1) {

                if (mT==1){//所有人
					setsetIntentPerson();
//                    BeauInfoShareSet.getInstance().setChangeDao();
				}else if(mT==2){//更改记录类型

					setIntentRecord();
				}
			}else if (position == ListUtils.getSize(jsonObject) + 2 && ishaveshare) {//分享
				BeauInfoShareSet.getInstance().setShareDao();

			}else if (SaveTemporaryData.isCalling){
//				if (position == ListUtils.getSize(jsonObject) + 3){
//					SaveTemporaryData.mSmart = "call";
//				}
			}
		}
		public void setIntentRecord(){
			Intent intents = new Intent(context, ChangeRecordActivity.class);
			intents.putExtra("LIST", (Serializable) recordList);
			intents.putExtra("mEntityId",mEntityId);
			intents.putExtra("mType",mType);
			context.startActivity(intents);
		}
		public void setsetIntentPerson(){
			Intent intents = new Intent(context, ChangePersonActivity.class);
			intents.putExtra("mPersionName",mPersionName);
			intents.putExtra("mPersionNameIds",mPersionNameIds);
			intents.putExtra("OwerName",OwerName);
			intents.putExtra("OwerNameID",OwerNameID);
			intents.putExtra("mPname",mPname);
			intents.putExtra("mObjId",mObjId);
			intents.putExtra("mObjName",mObjName);
			intents.putExtra("mEntityNameIDs",mEntityNameID);
			intents.putExtra("mEntityIds",mEntityId);

			context.startActivity(intents);
		}
}
